<template>
  <div
    class="combo-promotion-page min-h-screen bg-gradient-to-br from-purple-50 via-pink-50 to-purple-100"
  >
    <!-- Hero Section -->
    <div
      class="relative overflow-hidden bg-gradient-to-r from-purple-600 via-pink-600 to-purple-700"
    >
      <div class="absolute inset-0">
        <div class="absolute inset-0 bg-black opacity-20"></div>
        <div class="absolute top-0 left-0 w-full h-full">
          <div
            class="absolute top-10 left-10 w-32 h-32 bg-white bg-opacity-10 rounded-full animate-pulse"
          ></div>
          <div
            class="absolute top-20 right-20 w-24 h-24 bg-white bg-opacity-10 rounded-full animate-pulse delay-1000"
          ></div>
          <div
            class="absolute bottom-10 left-1/3 w-40 h-40 bg-white bg-opacity-10 rounded-full animate-pulse delay-2000"
          ></div>
        </div>
      </div>

      <div class="relative container mx-auto px-4 py-16">
        <div class="text-center text-white">
          <h1 class="text-5xl font-bold mb-4 animate-fade-in">
            <span
              class="bg-gradient-to-r from-yellow-300 to-pink-300 bg-clip-text text-transparent"
            >
              套餐促销
            </span>
          </h1>
          <p class="text-xl mb-8 opacity-90 animate-fade-in-delay">
            精选商品组合，超值优惠价格
          </p>
          <div class="flex justify-center space-x-8 text-sm">
            <div class="flex items-center">
              <div
                class="w-3 h-3 bg-yellow-400 rounded-full mr-2 animate-ping"
              ></div>
              <span>精选组合</span>
            </div>
            <div class="flex items-center">
              <div
                class="w-3 h-3 bg-green-400 rounded-full mr-2 animate-ping delay-500"
              ></div>
              <span>超值优惠</span>
            </div>
            <div class="flex items-center">
              <div
                class="w-3 h-3 bg-blue-400 rounded-full mr-2 animate-ping delay-1000"
              ></div>
              <span>限时特惠</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="container mx-auto px-4 py-8">
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <el-skeleton :rows="5" animated />
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="container mx-auto px-4 py-8">
      <div class="bg-white rounded-2xl shadow-lg p-6 text-center">
        <el-icon size="48" class="text-gray-400 mb-4"><Warning /></el-icon>
        <p class="text-gray-600 mb-4">{{ error }}</p>
        <el-button type="primary" @click="fetchPromotions">重新加载</el-button>
      </div>
    </div>

    <!-- Content -->
    <div v-else class="container mx-auto px-4 py-8">
      <!-- Combo Promotions Grid -->
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-6">套餐促销活动</h3>

        <div v-if="promotions.length === 0" class="text-center py-12">
          <el-icon size="64" class="text-gray-300 mb-4"
            ><ShoppingBag
          /></el-icon>
          <p class="text-gray-500 text-lg">暂无套餐促销</p>
          <p class="text-gray-400 text-sm mt-2">敬请期待更多优惠套餐</p>
        </div>

        <div
          v-else
          class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
        >
          <div
            v-for="combo in promotions"
            :key="combo.billNo"
            class="bg-white rounded-2xl shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl hover:-translate-y-2 group"
          >
            <!-- Combo Header -->
            <div
              class="bg-gradient-to-r from-purple-500 to-pink-500 p-6 text-white relative overflow-hidden"
            >
              <div class="absolute inset-0 bg-black bg-opacity-10"></div>
              <div class="relative z-10">
                <h3 class="text-xl font-bold mb-2">{{ combo.promName }}</h3>
                <p class="text-sm opacity-90">{{ combo.billCode }}</p>
                <div class="absolute top-4 right-4">
                  <div
                    class="bg-white bg-opacity-20 px-3 py-1 rounded-full text-xs font-bold"
                  >
                    {{ getPromotionStatus(combo) }}
                  </div>
                </div>
              </div>
              <div
                class="absolute -top-4 -right-4 w-24 h-24 bg-white bg-opacity-10 rounded-full"
              ></div>
            </div>

            <!-- Combo Items -->
            <div class="p-6">
              <div class="space-y-4 mb-6">
                <div
                  v-for="(item, itemIndex) in combo.details.slice(0, 3)"
                  :key="itemIndex"
                  class="p-4 bg-purple-50 rounded-lg border"
                >
                  <!-- 商品名称单独一行 -->
                  <div class="flex items-start gap-2 mb-2">
                    <h5 class="text-sm font-medium text-gray-800 flex-1">
                      {{ item.goodsInfo.title }}
                    </h5>
                  </div>

                  <!-- 生产厂家单独一行 -->
                  <p class="text-xs text-gray-600 mb-3">
                    {{ item.goodsInfo.manufacturer }}
                  </p>

                  <!-- 图片和价格信息在同一列 -->
                  <div class="flex items-start space-x-4">
                    <div>
                      <img
                        :src="getImageSrc(item.goodsInfo.mainPic)"
                        :alt="item.goodsInfo.title"
                        class="w-20 h-20 object-cover rounded-lg border border-gray-200 flex-shrink-0"
                        @error="handleImgError"
                      />
                      <p class="text-xs text-gray-600">
                        单价: ¥{{ Number(item.taxprice).toFixed(2) }}
                      </p>
                      <p class="text-sm font-bold text-purple-600">
                        总价: ¥{{
                          (Number(item.taxprice) * Number(item.num)).toFixed(2)
                        }}
                      </p>
                      <p class="text-xs text-gray-500 line-through">
                        原价: ¥{{
                          (
                            Number(item.goodsInfo.price) * Number(item.num)
                          ).toFixed(2)
                        }}
                      </p>
                    </div>

                    <div class="flex-1 min-w-0">
                      <div class="flex flex-wrap items-center gap-1 mb-2">
                        <el-tag
                          size="small"
                          class="!text-xs !px-2 !py-1 border !bg-blue-50 !border-blue-100 !text-gray-700"
                          >{{ item.goodsInfo.goodsSpec }}</el-tag
                        >
                        <el-tag
                          size="small"
                          class="!text-xs !px-2 !py-1 border !bg-blue-50 !border-blue-100 !text-gray-700"
                          >{{ item.goodsInfo.unit }}</el-tag
                        >
                      </div>
                      
                      <!-- 近效期信息 -->
                      <div v-if="item.goodsInfo.nearestExpiredDate" class="mb-2">
                        <div class="flex items-center gap-2">
                          <span class="text-xs text-gray-500">有效期:</span>
                          <span class="text-xs text-orange-600 font-medium">{{ formatDate(item.goodsInfo.nearestExpiredDate) }}</span>
                        </div>
                      </div>
                      
                      <p class="text-xs text-gray-500">
                        数量: {{ Number(item.num) }}{{ item.goodsInfo.unit }}
                      </p>
                    </div>
                  </div>
                </div>

                <div
                  v-if="combo.details.length > 3"
                  class="text-center text-sm text-gray-500 py-2"
                >
                  还有 {{ combo.details.length - 3 }} 个商品...
                </div>
              </div>

              <!-- Price Summary -->
              <div
                class="bg-gradient-to-r from-purple-50 to-pink-50 rounded-lg p-4 mb-4"
              >
                <div class="flex items-center justify-between mb-2">
                  <span class="text-sm text-gray-600">套餐价格:</span>
                  <span class="text-xl font-bold text-purple-600"
                    >¥{{ calculateTotalPrice(combo) }}</span
                  >
                </div>
                <div class="flex items-center justify-between mb-2">
                  <span class="text-sm text-gray-600">原价总计:</span>
                  <span class="text-sm text-gray-500 line-through"
                    >¥{{ calculateOriginalTotal(combo) }}</span
                  >
                </div>
                <div class="flex items-center justify-between">
                  <span class="text-sm text-gray-600">节省金额:</span>
                  <span class="text-lg font-bold text-red-600"
                    >¥{{ calculateSavings(combo) }}</span
                  >
                </div>
              </div>

              <!-- Validity Period -->
              <div class="text-xs text-gray-500 mb-4">
                有效期: {{ formatDate(combo.startTime) }} -
                {{ formatDate(combo.endTime) }}
              </div>

              <!-- Action Buttons -->
              <div class="flex space-x-3">
                <button
                  @click="viewComboDetails(combo)"
                  class="flex-1 py-2 px-4 border border-purple-300 rounded-lg text-purple-600 hover:bg-purple-50 transition-colors"
                >
                  查看详情
                </button>
                <button
                  @click="createComboOrder(combo)"
                  :disabled="!isPromotionActive(combo) || isCreatingComboOrder"
                  class="flex-1 py-2 px-4 rounded-lg font-medium transition-all duration-200"
                  :class="
                    isPromotionActive(combo) && !isCreatingComboOrder
                      ? 'bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white'
                      : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  "
                >
                  {{ isPromotionActive(combo) 
                    ? (isCreatingComboOrder ? '购买中...' : getButtonText(combo))
                    : getButtonText(combo) }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- How it works -->
      <div class="bg-white rounded-2xl shadow-lg p-6 mt-8">
        <h3 class="text-xl font-bold text-gray-800 mb-6">套餐优势</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="text-center">
            <div
              class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4"
            >
              <el-icon size="24" class="text-purple-600"><Box /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">精选组合</h4>
            <p class="text-sm text-gray-600">
              专业搭配，科学组合，满足不同需求
            </p>
          </div>
          <div class="text-center">
            <div
              class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4"
            >
              <el-icon size="24" class="text-purple-600"><PriceTag /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">超值优惠</h4>
            <p class="text-sm text-gray-600">
              套餐价格远低于单品购买，省钱更省心
            </p>
          </div>
          <div class="text-center">
            <div
              class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4"
            >
              <el-icon size="24" class="text-purple-600"
                ><ShoppingCart
              /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">直接下单</h4>
            <p class="text-sm text-gray-600">
              跳过购物车，直接生成订单，购买更快捷
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- Combo Detail Modal -->
    <el-dialog
      v-model="detailModalVisible"
      :title="selectedCombo?.promName"
      width="80%"
      max-width="1000px"
      class="combo-detail-modal"
    >
      <div v-if="selectedCombo" class="space-y-6">
        <!-- Combo Info -->
        <div class="bg-gradient-to-r from-purple-50 to-pink-50 rounded-lg p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h4 class="font-semibold text-gray-800 mb-3">套餐信息</h4>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-600">套餐名称:</span>
                  <span class="font-medium">{{ selectedCombo.promName }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">套餐编号:</span>
                  <span class="font-medium">{{ selectedCombo.billCode }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">有效期:</span>
                  <span class="font-medium"
                    >{{ formatDate(selectedCombo.startTime) }} -
                    {{ formatDate(selectedCombo.endTime) }}</span
                  >
                </div>
              </div>
            </div>

            <div>
              <h4 class="font-semibold text-gray-800 mb-3">价格信息</h4>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-600">套餐价格:</span>
                  <span class="text-lg font-bold text-purple-600"
                    >¥{{ calculateTotalPrice(selectedCombo) }}</span
                  >
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">原价总计:</span>
                  <span class="text-gray-500 line-through"
                    >¥{{ calculateOriginalTotal(selectedCombo) }}</span
                  >
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">节省金额:</span>
                  <span class="text-lg font-bold text-red-600"
                    >¥{{ calculateSavings(selectedCombo) }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Detailed Items List -->
        <div>
          <h4 class="font-semibold text-gray-800 mb-3">套餐商品详情</h4>
          <div class="space-y-4">
            <div
              v-for="(item, index) in selectedCombo.details"
              :key="index"
              class="p-4 bg-gray-50 rounded-lg border"
            >
              <!-- 商品名称单独一行 -->
              <div class="flex items-start gap-2 mb-2">
                <h5 class="font-medium text-gray-800 flex-1">
                  {{ item.goodsInfo.title }}
                </h5>
              </div>

              <!-- 生产厂家单独一行 -->
              <p class="text-sm text-gray-600 mb-3">
                生产厂家: {{ item.goodsInfo.manufacturer }}
              </p>

              <!-- 图片和价格信息在同一列 -->
              <div class="flex items-start space-x-4">
                <img
                  :src="getImageSrc(item.goodsInfo.mainPic)"
                  :alt="item.goodsInfo.title"
                  class="w-24 h-24 object-cover rounded-lg flex-shrink-0"
                  @error="handleImgError"
                />
                <div class="flex-1 min-w-0">
                  <div class="flex flex-wrap items-center gap-2 mb-2">
                    <el-tag
                      size="small"
                      class="border !bg-blue-50 !border-blue-100 !text-gray-700"
                      >{{ item.goodsInfo.goodsSpec }}</el-tag
                    >
                    <el-tag
                      size="small"
                      class="border !bg-blue-50 !border-blue-100 !text-gray-700"
                      >{{ item.goodsInfo.unit }}</el-tag
                    >
                  </div>
                  <div class="flex items-center gap-2 mb-2">
                    <el-tag
                      size="small"
                      class="border !bg-gray-50 !border-gray-200 !text-gray-600"
                      >{{ item.goodsInfo.qCategory }}</el-tag
                    >
                  </div>
                  
                  <!-- 近效期信息 -->
                  <div v-if="item.goodsInfo.nearestExpiredDate" class="mb-2">
                    <div class="flex items-center gap-2">
                      <span class="text-xs text-gray-500">有效期:</span>
                      <span class="text-xs text-orange-600 font-medium">{{ formatDate(item.goodsInfo.nearestExpiredDate) }}</span>
                    </div>
                  </div>
                  
                  <div class="packaging-info space-y-1">
                    <!-- 包装类型行 -->
                    <div class="flex items-center gap-2">
                      <el-tag 
                        size="small" 
                        :type="item.goodsInfo.midpack > 1 ? 'success' : 'info'" 
                        :class="item.goodsInfo.midpack > 1 ? '!bg-green-50' : '!bg-blue-50'"
                      >
                        {{ item.goodsInfo.midpack > 1 ? '中包装' : '件包装' }}
                      </el-tag>
                      <span class="text-sm text-gray-600">
                        {{ item.goodsInfo.midpack > 1 ? `${item.goodsInfo.midpack}${item.goodsInfo.unit}` : '件包装销售' }}
                      </span>
                    </div>
                    
                    <!-- 拆零支持行 -->
                    <div v-if="item.goodsInfo.midpack > 1" class="flex items-center">
                      <el-tag 
                        size="small" 
                        :type="item.goodsInfo.isMidpackSaleDisabled === 0 ? 'success' : 'warning'"
                        effect="plain"
                        class="!text-xs"
                      >
                        {{ item.goodsInfo.isMidpackSaleDisabled === 0 ? '支持拆零' : '不支持拆零' }}
                      </el-tag>
                      <span v-if="item.goodsInfo.isMidpackSaleDisabled === 1" class="text-xs text-orange-600 ml-2">
                        需按{{ item.goodsInfo.midpack }}{{ item.goodsInfo.unit }}倍数购买
                      </span>
                    </div>
                  </div>
                </div>
                <div class="text-right flex-shrink-0">
                  <p class="text-sm text-gray-600 mb-1">
                    数量: {{ item.num }}{{ item.goodsInfo.unit }}
                  </p>
                  <p class="text-sm text-gray-600">
                    单价: ¥{{ Number(item.taxprice).toFixed(2) }}
                  </p>
                  <p class="text-lg font-bold text-purple-600">
                    总价: ¥{{
                      (Number(item.taxprice) * Number(item.num)).toFixed(2)
                    }}
                  </p>
                  <p class="text-sm text-gray-500 line-through">
                    原价: ¥{{
                      (Number(item.goodsInfo.price) * Number(item.num)).toFixed(
                        2
                      )
                    }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Warning,
  ShoppingBag,
  Box,
  PriceTag,
  ShoppingCart,
} from "@element-plus/icons-vue";
import { promotionApi } from "@/api";
import type { ComboPromotion } from "@/api/modules/promotion";
import {
  handleImageError as handleImgError,
  getImageSrc,
} from "@/lib/imageUtils";

const router = useRouter();
const loading = ref(true);
const error = ref("");
const promotions = ref<ComboPromotion[]>([]);
const detailModalVisible = ref(false);
const selectedCombo = ref<ComboPromotion | null>(null);

// Methods
async function fetchPromotions() {
  try {
    loading.value = true;
    error.value = "";

    const response = await promotionApi.getPromotionsByType("TC");

    // response is ApiResponse<Promotion[]> due to response interceptor
    if (response.code === 1000 && response.data) {
      // Filter by Chinese promType or English promType and only active promotions
      const allPromotions = (response.data || []).filter(
        (p: any) => p.promType === "TC" || p.promType === "套餐"
      ) as ComboPromotion[];
      
      // Only show non-ended promotions (including not started and active)
      promotions.value = allPromotions.filter(promotion => !isPromotionEnded(promotion));
    } else {
      throw new Error(response.message || "获取套餐促销失败");
    }
  } catch (err: any) {
    error.value = err.message || "网络错误，请稍后重试";
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
}

function isPromotionActive(promotion: ComboPromotion): boolean {
  const now = new Date();
  const startTime = new Date(promotion.startTime);
  const endTime = new Date(promotion.endTime);

  return promotion.status === 1 && now >= startTime && now <= endTime;
}

function isPromotionEnded(promotion: ComboPromotion): boolean {
  const now = new Date();
  const endTime = new Date(promotion.endTime);

  return promotion.status === 0 || now > endTime;
}

function getPromotionStatus(promotion: ComboPromotion): string {
  const now = new Date();
  const startTime = new Date(promotion.startTime);
  const endTime = new Date(promotion.endTime);

  if (promotion.status === 0) return "已停用";
  if (now < startTime) return "未开始";
  if (now > endTime) return "已结束";
  return "进行中";
}

function getButtonText(combo: ComboPromotion): string {
  const now = new Date();
  const startTime = new Date(combo.startTime);
  const endTime = new Date(combo.endTime);

  if (combo.status === 0) return "已停用";
  if (now < startTime) return "未开始";
  if (now > endTime) return "已结束";
  return "立即购买";
}

function calculateTotalPrice(combo: ComboPromotion): string {
  const total = combo.details.reduce(
    (sum, item) => sum + Number(item.taxprice) * Number(item.num),
    0
  );
  return total.toFixed(2);
}

function calculateOriginalTotal(combo: ComboPromotion): string {
  const total = combo.details.reduce(
    (sum, item) => sum + Number(item.goodsInfo.price) * item.num,
    0
  );
  return total.toFixed(2);
}

function calculateSavings(combo: ComboPromotion): string {
  const original = parseFloat(calculateOriginalTotal(combo));
  const current = parseFloat(calculateTotalPrice(combo));
  return (original - current).toFixed(2);
}

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
}

function viewComboDetails(combo: ComboPromotion) {
  selectedCombo.value = combo;
  detailModalVisible.value = true;
}

// 套餐订单创建状态
const isCreatingComboOrder = ref(false)

async function createComboOrder(combo: ComboPromotion) {
  if (!isPromotionActive(combo)) {
    const status = getPromotionStatus(combo);
    ElMessage.warning(`套餐活动${status}`);
    return;
  }

  if (isCreatingComboOrder.value) {
    return;
  }

  isCreatingComboOrder.value = true;

  try {
    // 确认对话框
    await ElMessageBox.confirm(
      `确认购买套餐"${combo.promName}"吗？\n套餐价格：¥${calculateTotalPrice(
        combo
      )}\n原价总计：¥${calculateOriginalTotal(
        combo
      )}\n节省金额：¥${calculateSavings(combo)}`,
      "确认购买套餐",
      {
        confirmButtonText: "确认购买",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await promotionApi.createComboOrder({
      billNo: combo.billNo,
      remark: `套餐订单：${combo.promName}`,
    });

    if (response.code === 1000) {
      ElMessage.success(`套餐订单创建成功！订单号：${response.data.orderNum}`);
      // Navigate to my orders page
      router.push("/my-orders");
    } else {
      throw new Error(response.message || "创建订单失败");
    }
  } catch (error: any) {
    if (error === "cancel") {
      // 用户取消，不显示错误信息
      return;
    }
    ElMessage.error(error.message || "创建订单失败，请重试");
  } finally {
    isCreatingComboOrder.value = false;
  }
}

// Lifecycle
onMounted(() => {
  fetchPromotions();
});
</script>

<style scoped>
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fade-in-delay {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 1s ease-out;
}

.animate-fade-in-delay {
  animation: fade-in-delay 1s ease-out 0.3s both;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 优化弹窗样式 */
:deep(.combo-detail-modal .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

/* 优化标签间距 */
.el-tag + .el-tag {
  margin-left: 4px;
}

/* 包装信息样式 */
.packaging-info {
  background: #fafafa;
  border-radius: 4px;
  padding: 6px 8px;
  border: 1px solid #f0f0f0;
  margin-top: 8px;
}

.packaging-info .el-tag {
  border-radius: 2px;
  font-weight: 500;
}

.packaging-info .el-tag--small {
  height: 18px;
  line-height: 16px;
  padding: 0 4px;
  font-size: 11px;
}

/* 原有样式 */
.combo-card {
  transition: all 0.3s ease;
  border: 1px solid #e1e5e9;
}

.combo-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.combo-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.status-indicator {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}
</style>
